import cv2
import numpy as np

import cv2, os


class TagColor:
    def __init__(self):
        self.root = "D://vision/backup"
        self.boundaries = [
            ([80, 80, 80], [140, 140, 140]),
        ]
# 根据mask变成了黑白
    def show_filter(self, file='a.png'):
        d = self.mask(file)
        mask = d == 1
        not_mask = mask == False
        d = cv2.imread(file)
        gray = cv2.cvtColor(d, cv2.COLOR_BGR2GRAY)
# 把颜色范围内的设置黑色
        gray[mask] = 0
        gray[not_mask] = 255

        cv2.imshow("images",gray)
        cv2.waitKey(0)
        cv2.imwrite(f'./b.png',gray)


    def show(self, img, mask):
        output = cv2.bitwise_and(img, img, mask=mask)
        cv2.imshow("images", np.hstack([img, output]))
        cv2.waitKey(0)
# 根据色差找到mask
    def mask(self, file='a.png'):
        raw = f"{self.root}/{file}"
        img = cv2.imread(raw)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

        h, w, _ = img.shape
        init = np.zeros((h, w), dtype='uint8')
        for (lower, upper) in self.boundaries:
            # create NumPy arrays from the boundaries
            lower = np.array(lower, dtype="uint8")
            upper = np.array(upper, dtype="uint8")
            mask = cv2.inRange(img, lower, upper)
            true_false = np.ma.mask_or(init, mask)
            init = true_false.astype("uint8")
        # self.show(img, init)
        return init
# 根据黑白照contour
    def controur(self):

        img = cv2.imread('b.png')
        h,w,_=img.shape
        total=h*w
        imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        blank = np.zeros(img.shape, dtype='uint8')
        # 找的是黑色的
        ret, thresh = cv2.threshold(imgray, 0, 50,
                                    cv2.THRESH_BINARY)

        contours, hierarchy = cv2.findContours(thresh,
                                               cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

        # cv2.drawContours(blank, contours, -1, (0, 0, 255), 1)
        # cv2.drawContours(blank, contours, -1, (255, 255, 255), 2)
        black=0
        for c in contours:
            M = cv2.moments(c)
            n = cv2.contourArea(c)
            black=black+n
            if M["m00"] != 0:
                cX = int(M["m10"] / M["m00"])
                cY = int(M["m01"] / M["m00"])
            else:
                cX, cY = 0, 0
            cv2.putText(blank, "C", (cX, cY), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255))
        cv2.imshow('image',imgray)
        cv2.imshow('contours', blank)
        # cv2.imshow('threshold', thresh)
        print (black,total,black/total)

        cv2.waitKey(0)


if __name__ == '__main__':
    t = TagColor()
    # t.mask()
    # t.show_filter()
    t.controur()
